package com.qiyi.tm.taskmanager.other;



import com.qiyi.tm.taskmanager.Task;
import com.qiyi.tm.taskmanager.TaskManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventQueue;
import ohos.eventhandler.EventRunner;


/**
 * use to handel main thread idle tasks
 */
public class IdleScheduler {
    private int count;
    private IdleHandler handler;
    private EventHandler mainHandler = new EventHandler(EventRunner.getMainEventRunner());
    private Runnable pingUIRunnable = new Runnable(){
        @Override
        public void run() {
            // do nothing
        }
    };

    /**
     * Call when a ui thread idle task is registered
     */
    public void increase() {
        synchronized (this) {
            count++;
            if (handler == null) {
                handler = new IdleHandler();
                final IdleHandler handle = handler;
                new Task() {
                    @Override
                    public void doTask() {
                        if (handle.started) {
//                            EventRunner..addIdleHandler(handle);
                           // EventRunner.create().setLogger(handle);

                        }
                    }
                }.postUI();
            }
        }
    }

    /**
     * Call when a ui thread idle task is unregistered
     */
    public void decrease() {
        synchronized (this) {
            count--;
            if (count == 0) {
                final IdleHandler handle = handler;
                if (handle != null) {
                    handle.stop();
                }
                new Task() {
                    @Override
                    public void doTask() {
//                        Looper.myQueue().removeIdleHandler(handle);
                    }
                }.postUI();
                handler = null;
            }
        }
        //fix UI thread idle need UI action to trigger up
        mainHandler.postTask(pingUIRunnable);
    }

    static class IdleHandler /*implements EventQueue.IdleHandler*/ {

        boolean started;

        public IdleHandler() {
            started = true;
        }

        public void stop() {
            started = false;
        }

       // @Override
        public boolean queueIdle() {
            TaskManager.getInstance().triggerIdleRun();
            return started;
        }
    }

}
